package com.zzyl.nursing.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 预约相关定时任务配置
 */
@Component
public class ReservationJobConfig implements CommandLineRunner {
    
    private static final Logger log = LoggerFactory.getLogger(ReservationJobConfig.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Override
    public void run(String... args) throws Exception {
        // 注册预约过期处理任务
        registerReservationExpiredJob();
    }
    
    /**
     * 注册预约过期处理任务
     */
    private void registerReservationExpiredJob() {
        try {
            // 检查是否已存在同名任务
            Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_job WHERE job_name = ? AND job_group = ?",
                Integer.class, "预约过期处理任务", "DEFAULT");
            
            if (count != null && count > 0) {
                log.info("预约过期处理任务已存在，无需重复注册");
                return;
            }
            
            // 插入新的定时任务记录
            jdbcTemplate.update(
                "INSERT INTO sys_job (job_name, job_group, invoke_target, cron_expression, misfire_policy, concurrent, status, create_by, create_time, remark) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)",
                "预约过期处理任务",
                "DEFAULT",
                "reservationExpiredJob.execute",
                "0 0/30 * * * ?",  // 每30分钟执行一次
                "3",  // 放弃执行
                "1",  // 禁止并发
                "0",  // 正常状态
                "1",  // 创建人ID
                "处理过期预约"
            );
            
            log.info("预约过期处理任务注册成功");
        } catch (Exception e) {
            log.error("注册预约过期处理任务时发生异常", e);
        }
    }
}
